#include <sys/types.h>
#include <string.h>
#include "url_info.h"

int recv_header(int socket_id, struct url_info *url_info)
{
	register int count = 6;
	register int index = 0;
	register int nread;
	url_info->header = url_info->buff + 2;
	while ( count --  && index < HEADER_LEN)
	{
		if ((nread = recv(socket_id, url_info->header+index, HEADER_LEN-index, 0)) < 0)
		{
			return -1;
		}	
		index += nread;
		if (index > 4 && *(u_int32_t*)(url_info->header + (index-4)) == *(u_int32_t*)"\r\n\r\n")
		{
			url_info->header[index] = 0;
			url_info->hlen = index;
			return index;
		}
	}
	return -1;
}

int process_header_line(struct url_info *url)
{
	char *loc1;
	char *loc2;
	char *header = url->header;

	url->range = 0;
	url->hnum = 0;

	loc1 = strstr(header, "\r\n");
	if (!(loc1 && (loc1 - header) >=14 && *(u_int32_t*)header == *(u_int32_t*)"GET "))
	{
		return -1;
	}
	*(loc1-9) = 0;
	url->url = url->buff;
	memcpy(url->url, "http:/", 6);

	loc1 += 2;
	while (loc2 = strstr(loc1, "\r\n"))
	{
		if (loc1 == loc2)
			break;
		*loc2 = 0;
		if (strncmp(loc1, "Range: bytes=", 13) == 0)
			url->range = loc1;
		else if(strncmp(loc1, "Host: ", 6) == 0 )
				url->host = loc1 + 6;
		else if (strncmp(loc1, "Connection:", 11) != 0 )
			url->hline[url->hnum++] = loc1;
		loc1 = loc2 + 2;
	}
	return 1;
}

int locate_filename_and_qmark(struct url_info *url_info)
{
	char *floc;
	char *url = url_info->url + 7;

	url_info->filenamelen = 0;
	url_info->filename = url_info->qmark = 0;

	floc = rindex(url, '/');

	if (floc)
		url_info->filename = floc+1;
	else
		url_info->filename = url;

	if (*url_info->filename == 0)
	{
		url_info->filename = 0;
		return 1;
	}

	if (*url_info->filename == '?')
	{
		url_info->qmark = url_info->filename;
		url_info->filename = 0;
		return 1;
	}

	url_info->qmark = index(url_info->filename, '?');

	if (url_info->qmark)
		url_info->filenamelen = url_info->qmark - url_info->filename;
	else
		url_info->filenamelen = strlen(url_info->filename);

	return 1;
}
